﻿package org.hyy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hyy.dao.CategoryDAO;
import org.hyy.dao.ProductDAO;
import org.hyy.vo.Category;
import org.hyy.vo.Product;

public class AddProduct extends HttpServlet {

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取参数
		request.setCharacterEncoding("GBK");
		int step = Integer.parseInt(request.getParameter("step"));
		
		//声明
		ProductDAO productDAO = null;
		CategoryDAO categoryDAO = null;
		List<Category> categories = null;
		Product product = null;
		
		if(step == 1){
			categoryDAO = new CategoryDAO();
			categories = new ArrayList<Category>();
			
			categories = categoryDAO.GetCatergories();
			List<Category> list = new ArrayList<Category>();
			for(int i=0;i<categories.size();i++){
				Category category = new Category();
				category = categories.get(i);
				//第二层类别
				if(category.getGrade()==2){
					list.add(category);
				}
			}
			request.setAttribute("categories", list);
			request.getRequestDispatcher("admin/addProduct.jsp").forward(request, response);
		}
		if(step == 2){
			
			//获取参数
			String name = request.getParameter("name");
			String descr = request.getParameter("descr");
			double normalPrice = Double.parseDouble(request.getParameter("normalPrice"));
			double memberPrice = Double.parseDouble(request.getParameter("memberPrice"));
			int categoryId = Integer.parseInt(request.getParameter("categoryId"));
			
			product = new Product();
			product.setName(name);
			product.setDescr(descr);
			product.setNormalPrice(normalPrice);
			product.setMemberPrice(memberPrice);
			product.setPdate(new Date());
			product.setCategoryId(categoryId);
			
			productDAO = new ProductDAO();
			productDAO.add(product);
			
			response.sendRedirect("admin/adminhome.jsp");
		}
		
	}

}
